package cn.dada.dadarecipes.user.personal_account.service.impl;

import cn.dada.dadarecipes.base.enums.PersonalAccountRecordEnum;
import cn.dada.dadarecipes.user.personal_account.mapper.PersonalAccountMapper;
import cn.dada.dadarecipes.user.personal_account.pojo.dto.PersonalAccountBalanceParam;
import cn.dada.dadarecipes.user.personal_account.pojo.vo.PersonalAccountVO;
import cn.dada.dadarecipes.user.personal_account.service.PersonalAccountService;
import cn.dada.dadarecipes.user.personal_account_record.mapper.PersonalAccountRecordMapper;
import cn.dada.dadarecipes.user.personal_account_record.pojo.dto.PersonalAccountRecordLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class PersonalAccountServiceImpl implements PersonalAccountService {
    @Autowired
    PersonalAccountMapper personalAccountMapper;

    @Autowired
    PersonalAccountRecordMapper personalAccountRecordMapper;
    @Override
    public List<PersonalAccountVO> queryBalance(Long userId) {
        log.debug("用户查询:userId={}", userId);
        // 调用Mapper层方法查询用户账户余额
        List<PersonalAccountVO> personalAccountVO = personalAccountMapper.queryBalance(userId);
        return personalAccountVO;
    }

    @Override
    @Transactional
    public void balanceRecharge(PersonalAccountBalanceParam param) {
        log.debug("用户充值开始: personalAccount={}", param);

        // 参数校验
        if (param == null || param.getUserId() == null || param.getAmount() == null) {
            // 如果参数为空，记录警告日志并返回
            log.warn("参数错误: personalAccountBalanceParam={}", param);
            return;
        }

        if (param.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            // 如果充值金额不大于0，记录警告日志并返回
            log.warn("充值金额必须大于0: personalAccountBalanceParam={}", param);
            return;
        }

        // 查询用户账户信息
        List<PersonalAccountVO> accountList = personalAccountMapper.queryBalance(param.getUserId());
        if (accountList.isEmpty()) {
            // 如果用户账户不存在，记录警告日志并返回
            log.warn("用户账户不存在: userId={}", param.getUserId());
            return;
        }

        // 获取用户的账户信息
        PersonalAccountVO account = accountList.get(0);
        log.debug("查询到的账户信息: account={}", account);

        // 更新账户余额
        BigDecimal newBalance = account.getAccountBalance().add(param.getAmount());
        account.setAccountBalance(newBalance);
        log.debug("新的账户余额: newBalance={}", newBalance);
        // 更新数据库
        account.setAmount(param.getAmount());
        int updatedRows = personalAccountMapper.updateBalance(account);

        if (updatedRows != 1) {
            // 如果更新账户余额失败，记录警告日志并返回
            log.warn("更新账户余额失败，可能是并发冲突导致: userId={}, updatedRows={}", param.getUserId(), updatedRows);
            return;
        }


        // 记录充值记录
        PersonalAccountRecordLog record = new PersonalAccountRecordLog();
        record.setPersonalId(account.getId());
        record.setDate(new Date()); // 设置为当前日期
        record.setTime(new Date()); // 设置为当前时间
        record.setTransactionType(PersonalAccountRecordEnum.INCOME.getCode());
        record.setAmount(param.getAmount());
        record.setCounterparty(""); // 对方账户，这里假设为空

        // 设置 order_id 字段的值
        record.setOrderId(param.getUserId());

        // 格式化日期和时间用于日志输出
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = dateFormat.format(record.getDate());
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        String formattedTime = timeFormat.format(record.getTime());

        log.debug("创建的充值记录: record={} (日期格式化为: {}, 时间格式化为: {})", record, formattedDate, formattedTime);

        // 插入充值记录到数据库
        int insertedRows = personalAccountRecordMapper.insertRecord(record);
        if (insertedRows != 1) {
            // 如果插入账户记录失败，记录警告日志并返回
            log.warn("插入账户记录失败: userId={}, insertedRows={}", param.getUserId(), insertedRows);
            return;
        }

        log.info("用户充值成功: userId={}, amount={}, newBalance={}",
                param.getUserId(), param.getAmount(), newBalance);
    }
}
